package com.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class RSAUtils {

    /**
     * 密钥算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 加密算法RSA
     */
    public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1PADDING";

    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 获取公钥的key
     */
    public static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key
     */
    public static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 生成密钥对(公钥和私钥)
     */
    public static Map<String, Key> genKeyPair() {
        KeyPairGenerator keyPairGen;
        try {
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Key> keyMap = new HashMap<String, Key>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }


    /**
     * 私钥解密
     *
     * @param srcData    已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws UnsupportedEncodingException
     */
    public static String decryptByPrivateKey(String srcData, String privateKey) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        ByteArrayOutputStream out = null;
        try {
            byte[] keyBytes = Base64.decodeBase64(privateKey.getBytes());
            byte[] encryptedData = Base64.decodeBase64(srcData);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateK);
            int inputLen = encryptedData.length;
            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            return new String(decryptedData, "utf-8");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 公钥解密
     *
     * @param srcData   已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws UnsupportedEncodingException
     */
    public static String decryptByPublicKey(String srcData, String publicKey)  {
        ByteArrayOutputStream out = null;
        try {
            byte[] keyBytes = Base64.decodeBase64(publicKey.getBytes());
            byte[] encryptedData = Base64.decodeBase64(srcData.getBytes());
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicK);
            int inputLen = encryptedData.length;
            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            return new String(decryptedData, "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 公钥加密
     *
     * @param srcData   源数据
     * @param publicKey 公钥(BASE64编码)
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws UnsupportedEncodingException
     */
    public static String encryptByPublicKey(String srcData, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        ByteArrayOutputStream out = null;
        if (Objects.nonNull(srcData) || "".equals(srcData)) {
            try {
                byte[] keyBytes = Base64.decodeBase64(publicKey.getBytes());
                byte[] data = srcData.getBytes("utf-8");
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
                Key publicK = keyFactory.generatePublic(x509KeySpec);
                // 对数据加密
                Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                cipher.init(Cipher.ENCRYPT_MODE, publicK);
                int inputLen = data.length;
                out = new ByteArrayOutputStream();
                int offSet = 0;
                byte[] cache;
                int i = 0;
                // 对数据分段加密
                while (inputLen - offSet >= 0) {
                    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                        cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                    } else {
                        cache = cipher.doFinal(data, offSet, inputLen - offSet);
                    }
                    out.write(cache, 0, cache.length);
                    i++;
                    offSet = i * MAX_ENCRYPT_BLOCK;
                }
                byte[] encryptedData = out.toByteArray();
                return Base64.encodeBase64String(encryptedData);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            return null;
        }
    }

    /**
     * 私钥加密
     *
     * @param srcData    源数据
     * @param privateKey 私钥(BASE64编码)
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws UnsupportedEncodingException
     */
    public static String encryptByPrivateKey(String srcData, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        ByteArrayOutputStream out = null;
        try {
            byte[] keyBytes = Base64.decodeBase64(privateKey.getBytes());
            byte[] data = srcData.getBytes("utf-8");
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateK);
            int inputLen = data.length;
            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            return Base64.encodeBase64String(encryptedData);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取私钥
     *
     * @param keyMap 密钥对
     */
    public static String getPrivateKey(Map<String, Key> keyMap) {
        Key key = keyMap.get(PRIVATE_KEY);
        return Base64.encodeBase64String(key.getEncoded());
    }

    /**
     * 获取公钥
     *
     * @param keyMap 密钥对
     */
    public static String getPublicKey(Map<String, Key> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);

        System.out.println("转换前长度" + key.getEncoded().length);

//		return Base64Utils.encode(key.getEncoded());
        return Base64.encodeBase64String(key.getEncoded());
    }

    ////////////////////////////////////////////////////

    /**
     * 签名
     *
     * @param dataString       待签名数据
     * @param base64privateKey 密钥
     * @return String 数字签名
     * @throws Exception e
     * @author hyz
     * @createTime:2016年7月19日
     */
    public static String sign(String dataString, String base64privateKey) throws Exception {
        byte[] privateKey = Base64.decodeBase64(base64privateKey);
        byte[] data = dataString.getBytes();
        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //实例化Signature
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        //初始化Signature
        signature.initSign(priKey);
        //更新
        signature.update(data);
        return Base64.encodeBase64String(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param dataString      待校验数据
     * @param base64publicKey 公钥
     * @param signString      数字签名
     * @return boolean 校验成功返回true，失败返回false
     * @throws Exception e
     * @author hyz
     * @createTime:2016年7月19日
     */
    public static boolean verify(String dataString, String base64publicKey, String signString) throws Exception {

        byte[] sign = Base64.decodeBase64(signString);
        byte[] publicKey = Base64.decodeBase64(base64publicKey);
        byte[] data = dataString.getBytes();
        //转换公钥材料
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
        //产生公钥
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
        //实例化Signature
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        //初始化Signature
        signature.initVerify(pubKey);
        //更新
        signature.update(data);
        //验证
        return signature.verify(sign);
    }


    public static void main(String[] args) throws Exception {
        Map<String, Key> keymap = genKeyPair();
        String Base64privateKey = Base64.encodeBase64String(keymap.get(RSAUtils.PRIVATE_KEY).getEncoded());
        String Base64publicKey = Base64.encodeBase64String(keymap.get(RSAUtils.PUBLIC_KEY).getEncoded());
//        String v = "{\n" +
//                "    \"companyId\": 1000030754,\n" +
//                "    \"shopId\": \"1000180440\",\n" +
//                "    \"terminalId\": \"1000366771\",\n" +
//                "    \"cardInfo\": {\n" +
//                "        \"mobile\": \"15902222222\",\n" +
//                "        \"cardTypeId\": \"1000002963\"\n" +
//                "    }\n" +
//                "}";
        String v = "{\n" +
                "    \"groupID\":\"1000001056\",\n" +
                "    \"shopID\":1000180440,\n" +
                "    \"phone\":\"18832411123\",\n" +
                "}";
        //甲方进行数据的加密
        String s = encryptByPublicKey(v, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLQCS19NJqKWds7df/AGm6dfPs+iSkdgoaAbMy36bcC+JNeQ3+BrobF+g0053FiYgp+K701qyf9T/NmeE02JX74BHWGuIxfbMP1lI79fNnu3AS2cpfIgMqK1EIwChKHVsQ2YKEMRMLYCI3cS1dBLvDPZ93joEsN1d4PJ25pN79swIDAQAB");
        System.out.println(s);
    }
}
